﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using SharedLib.WinFormMVCFramework;
using System.Xml;
using TracyGUI.Model;
using System.IO;
using Tracy.DataModel;
using System.Windows.Forms;
using Tracy;
using TracyGUI.View;

namespace TracyGUI.Controller
{
    class ImportExportViewController : ControllerBase<IImportExportView>, IController<IImportExportView>
    {
        protected override IImportExportView ResolveView()
        {
            return Tracy.TracyFacade.Instance.DIContainer.Resolve<IImportExportView>();
        }


        ImportExportManager _importExportManager = new ImportExportManager();
        public ImportExportViewController()
        {
            View.DataImportFileSelected += new EventHandler<SharedLib.GenericEventArgs<string>>(View_DataImportFileSelected);
            View.DataExporting += new EventHandler<SharedLib.EnhancedEventArgs>(View_DataExporting);
            View.PhysicalFilesImporting += new EventHandler<SharedLib.EnhancedEventArgs>(View_PhysicalFilesImporting);
        }

        #region View Events
        void View_PhysicalFilesImporting(object sender, SharedLib.EnhancedEventArgs e)
        {
            Tracy.TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                //TODO: Assign Tags Automatically
                string entryName = e.Attributes["entry-name"] as string;
                string savePath = e.Attributes["save-path"] as string;
                List<string> filenames = e.Attributes["files"] as List<String>;
                _importExportManager.ImportPhysicalFiles(entryName, savePath, filenames);
            }, "UI Policy");
        }

        

        void View_DataExporting(object sender, SharedLib.EnhancedEventArgs e)
        {
            Tracy.TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                List<Entry> entries = e.Attributes["entries"] as List<Entry>;
                string file = e.Attributes["file"] as string;
                if (entries != null && !String.IsNullOrEmpty(file))
                {
                    XmlDocument doc = _importExportManager.ExportEntries(entries);
                    ZipHelper.ZipXml(doc, file);
                    MessageBox.Show(String.Format(TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryExported_Message"), entries.Count));
                }
            }, "UI Policy");
        }

        void View_DataImportFileSelected(object sender, SharedLib.GenericEventArgs<string> e)
        {
            Tracy.TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                if (File.Exists(e.Data))
                {
                    XmlDocument docToImport = ZipHelper.UnzipXml(e.Data);
                    List<Entry> entriesFound = new List<Entry>();
                    foreach (XmlElement entryNode in docToImport.SelectNodes("/entries/entry"))
                    {
                        entriesFound.Add(new Entry(entryNode));
                    }

                    if (entriesFound.Count == 0)
                    {
                        MessageBox.Show(Tracy.TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryImportNoEntryFound_Message"));
                    }
                    else
                    {
                        View.ShowAvailableEntries(entriesFound, entriesSelected =>
                        {
                            ImportingEntries(entriesSelected, docToImport);
                        });
                    }

                }
            }, "UI Policy");
        }
        #endregion

        private void ImportingEntries(List<Entry> entries, XmlDocument source)
        {
            if (entries != null && source != null)
            {
                List<Entry> entriesToUpdate = new List<Entry>();
                List<Entry> entriesToAdd = new List<Entry>();
                foreach (Entry entry in entries)
                {
                    //Check whether the entries already exist or not
                    Entry existingEntry = TracyFacade.Instance.EntryProvider.GetItemByName(entry.Name);
                    if (existingEntry != null)
                    {
                        entry.Properties["original-id"] = existingEntry.ID;//Set the id of the existing entry
                        entriesToUpdate.Add(entry);
                    }
                    else
                    {
                        entriesToAdd.Add(entry);
                    }
                }
                
                if (entriesToAdd.Count > 0)
                {
                    View.SelectFolderForNewEntries(TracyFacade.Instance.UserPreferencesManager.SavePath, folder =>
                    {
                        _importExportManager.ImportEntries(entriesToAdd, folder, source);
                        MessageBox.Show(String.Format(TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryImported_Message"), entriesToAdd.Count));
                    });
                }
                if (entriesToUpdate.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Entry entry in entriesToUpdate)
                    {
                        sb.Append(entry.Name);
                        sb.Append("\n");
                    }
                    if (MessageBox.Show(String.Format(TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryImportExisting_Message"), sb.ToString()), TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryImportExisting_Title"), MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        _importExportManager.ImportEntries(entriesToUpdate, TracyFacade.Instance.UserPreferencesManager.SavePath, source);
                        MessageBox.Show(String.Format(TracyFacade.Instance.LanguageManager.GetText("MessageBox_EntryUpdated_Message"), entriesToUpdate.Count));
                    }
                }
            }
        }

        
    }
}
